<?php

class EntityAdmin
{
    private $entityName;
    private $_db;


    public function __construct()
    {
        $this->_db = Db::getInstance();
    }
    
    public function setEntityName($entityName)
    {
        $this->entityName = $entityName;
    }
    
    public function entitiesList()
    {
        $entities = $this->_db->qr("select * from `entities`");
        
        return $entities;
    }
    
    public function addEntity($entityName, $viewName)
    {
        $this->_db->q("create table `".$entityName."` (`id` int primary key auto_increment, 
                                                       `nameid` varchar(255))");
        $this->_db->q("create table `".$entityName."_views` (`id` int primary key auto_increment, 
                                                             `nameid` varchar(255), 
                                                             `name` varchar(255), 
                                                             `sql` text)");
        $this->_db->q("create table `".$entityName."_names` (`id` int primary key auto_increment, 
                                                             `nameid` varchar(255),
                                                             `name` varchar(255),
                                                             `type` varchar(255),
                                                             `value` text)");
        $this->_db->q("insert into `entities` (`name`, `view_name`) values ('".$entityName."', '".$viewName."')");
        
        mkdir($_SERVER['DOCUMENT_ROOT'].'/themes/tables/'.$entityName);
        copy($_SERVER['DOCUMENT_ROOT'].'/admin/pattern/long.tpl', $_SERVER['DOCUMENT_ROOT'].'/themes/tables/'.$entityName.'/long.tpl');
        copy($_SERVER['DOCUMENT_ROOT'].'/admin/pattern/short.tpl', $_SERVER['DOCUMENT_ROOT'].'/themes/tables/'.$entityName.'/short.tpl');
    }
    
    public function showEntity ()
    {
        return $this->_db->qri("select * from `".$this->entityName."`");
    }
    
    public function showNames()
    {
        return $this->_db->qr("select * from `".$this->entityName."_names`");
    }
    
    public function getViewName()
    {
        $s = $this->_db->qr("select * from `entities` where `name` = '".$this->entityName."'");
        return $s[0]['view_name'];
    }
    
    public function deleteRow($entity, $row)
    {
        return $this->_db->q("delete from `".$entity."` where id = ".$row);
    }
}